import "react-cmdk/dist/cmdk.css";
import i18n from "@/local/i18n.ts";
import {adminRoutes, NavRouterObject} from "@/routes/admin.tsx";
import {useAppSelector} from "@/store/store.ts";
import {
    switchAdminCollapsedLeftNav,
    switchAdminShowBreadcrumb,
    switchAdminShowCmdk,
    switchFullScreen,
    switchTheme,
    switchVConsole
} from "@/store/system";
import {logout} from "@/store/user";
import {message} from "antd";
import {useEffect, useState} from "react";
import CommandPalette, {filterItems, getItemIndex, JsonStructureItem} from "react-cmdk";
import {CgDebug} from "react-icons/cg";
import {CiLogout} from "react-icons/ci";
import {FaLanguage} from "react-icons/fa";
import {FaHouse} from "react-icons/fa6";
import {MdOutlineZoomOutMap} from "react-icons/md";
import {TbLayoutSidebarLeftCollapse, TbLayoutSidebarRightCollapse, TbMoon, TbSun, TbSunMoon} from "react-icons/tb";
import {VscDebug} from "react-icons/vsc";
import {useDispatch} from "react-redux";
import {useNavigate} from "react-router-dom";

const Cmdk = () => {
    const [page, setPage] = useState<"root" | "projects">("root");
    const systemState = useAppSelector(state => state.system)
    const [search, setSearch] = useState("");
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const isAdminPage = location.pathname.includes("/admin/")

    // 通用快速操作
    const baseQuickActions:JsonStructureItem[] = [
        {
            id: "switch-theme",
            children: "切换主题(switch theme)",
            icon: () => systemState.theme == "dark" ? <TbSun/> : <TbMoon/>,
            onClick: () => {
                dispatch(switchTheme())
            }
        },
        {
            id: isAdminPage ? "back-front" :"back-admin",
            children:isAdminPage ? "返回前台(back-front)" : "返回后台(back-admin)",
            icon: () => <FaHouse/>,
            onClick: () => {
                navigate( isAdminPage ? "/home":"/admin")
            }
        },
        {
            id: "change-language",
            children: "切换语言(change-language)",
            icon: () => <FaLanguage/>,
            onClick: () => {
                i18n.changeLanguage(i18n.language == "cn" ? 'en' : 'cn')
            }
        },
        {
            id: "switch-full-screen",
            children: `${systemState.isFullScreen ? "退出全屏" : "全屏"}(switch full screen)`,
            icon: () => <MdOutlineZoomOutMap/>,
            onClick: () => {
                dispatch(switchFullScreen())
            }
        },
        {
            id: "log-out",
            children: "退出登录(logout)",
            icon: () => <CiLogout/>,
            onClick: () => {
                dispatch(logout())
            },
        },
    ]

    // 根据路由配置获取快速导航栏，目前仅支持三级路由
    const getQuickNavRoutes = () => {
        const quickNavRoutes: JsonStructureItem[] = []
        adminRoutes.forEach(route => {
            if (route.children) {
                route.children.forEach((child:NavRouterObject) => {
                    if (child.children) {
                        child.children.forEach((third:NavRouterObject) => {
                            quickNavRoutes.push({
                                id: `${route.key}/${child.key}/${third.key}`,
                                children: `${route.label}-${child.label}-${third.label}`,
                                icon: ()=> third.icon,
                                onClick: () => {
                                    navigate(`${route.path!}/${child.path!}/${third.path}`)
                                }
                            })
                        })
                    }else {
                        quickNavRoutes.push({
                            id: `${route.key}/${child.key}`,
                            children: `${route.label}-${child.label}`,
                            icon: ()=> child.icon,
                            onClick: () => {
                                navigate(`${route.path!}/${child.path!}`)
                            }
                        })
                    }

                })
            }else {
                quickNavRoutes.push({
                    id: route.key,
                    children: route.label,
                    icon: ()=> route.icon,
                    onClick: () => {
                        navigate(route.path!)
                    }
                })
            }
        })
        return quickNavRoutes
    }

    const adminFilteredItems = filterItems(
        [
            {
                heading: "快速导航",
                id: "quick-nav",
                items: [
                    ...getQuickNavRoutes()
                ],
            },
            {
                heading: "快速操作",
                id: "quick-action",
                items: [

                    {
                        id: "switch-collapse-left-nav",
                        children: `${systemState.adminCollapsedLeftNav ? "展开" : "收起"}侧边导航(switch collapse left nav)`,
                        icon: () => systemState.adminCollapsedLeftNav ? <TbLayoutSidebarRightCollapse/> :
                            <TbLayoutSidebarLeftCollapse/>,
                        onClick: () => {
                            dispatch(switchAdminCollapsedLeftNav())
                        }
                    },
                    {
                        id: "switch-show-breadcrumb",
                        children: `${systemState.adminShowBreadcrumb ? "隐藏" : "显示"}面包屑(switch breadcrumb)`,
                        icon: () => <TbSunMoon/>,
                        onClick: () => {
                            dispatch(switchAdminShowBreadcrumb())
                        }
                    },
                    ...baseQuickActions
                ],
            },
        ],
        search
    );

    const frontFilteredItems = filterItems(
        [
            {
                heading: "快速操作",
                id: "quick-action",
                items: [
                    {
                        id: "switch-vconsole",
                        children: `${systemState.enableVConsole ? "关闭" : "开启"}Vconsole(switch-vconsole)`,
                        icon: () => systemState.enableVConsole ? <CgDebug/> :<VscDebug/>,
                        onClick: () => {
                            dispatch(switchVConsole())
                        }
                    },
                    ...baseQuickActions
                ],

            },
        ],
        search
    );

    useEffect(() => {
        function handleKeyDown(e: KeyboardEvent) {

            // 支持shift + command + k  或者 command + k
            if (
                (e.shiftKey && (navigator?.platform?.toLowerCase().includes("mac")
                        ? e.metaKey
                        : e.ctrlKey) &&
                    e.key === "k")
                ||
                ((navigator?.platform?.toLowerCase().includes("mac")
                        ? e.metaKey
                        : e.ctrlKey) &&
                    e.key === "k")
            ) {
                e.preventDefault();
                e.stopPropagation();
                dispatch(switchAdminShowCmdk())
            }

            if (
                e.key == "Backspace" && search == ""
            ) {
                setPage("root");
            }
        }

        document.addEventListener("keydown", handleKeyDown);

        return () => {
            document.removeEventListener("keydown", handleKeyDown);
        };
    }, []);

    if (isAdminPage) {
        return (
            <CommandPalette
                onChangeSearch={setSearch}
                onChangeOpen={() => {
                    dispatch(switchAdminShowCmdk())
                }}
                placeholder={"快速搜索，快捷键: ⌘K"}
                search={search}
                isOpen={systemState.adminShowCmdk}
                page={page}
            >
                <CommandPalette.Page id="root">
                    {adminFilteredItems.length ? (
                        adminFilteredItems.map((list) => (
                            <CommandPalette.List key={list.id} heading={list.heading}>
                                {list.items.map(({id, ...rest}) => (
                                    <CommandPalette.ListItem
                                        key={id}
                                        index={getItemIndex(adminFilteredItems, id)}
                                        {...rest}
                                    />
                                ))}
                            </CommandPalette.List>
                        ))
                    ) : (
                        <CommandPalette.FreeSearchAction />
                    )}
                </CommandPalette.Page>

                <CommandPalette.Page id="projects">
                    <CommandPalette.List key={"1111"} heading="项目管理">
                        <CommandPalette.ListItem
                            id="projects-1"
                            index={0}
                            key={1}
                            onClick={() => {
                                message.success("Test1");
                            }}
                        >
                            Test1
                        </CommandPalette.ListItem>
                        <CommandPalette.ListItem
                            id="projects-2"
                            index={1}
                            key={2}
                            onClick={() => {
                                message.success("Test2");
                            }}
                        >
                            Test2
                        </CommandPalette.ListItem>
                        <CommandPalette.ListItem
                            id="projects-3"
                            index={2}
                            key={3}
                            onClick={() => {
                                message.success("Test3");
                            }}
                        >
                            Test3
                        </CommandPalette.ListItem>
                    </CommandPalette.List>
                </CommandPalette.Page>
            </CommandPalette>
        );
    } else {
        return <CommandPalette
            onChangeSearch={setSearch}
            onChangeOpen={() => {
                dispatch(switchAdminShowCmdk())
            }}
            search={search}
            isOpen={systemState.adminShowCmdk}
            page={page}
        >
            <CommandPalette.Page id="root">
                {frontFilteredItems.length ? (
                    frontFilteredItems.map((list) => (
                        <CommandPalette.List key={list.id} heading={list.heading}>
                            {list.items.map(({id, ...rest}) => (
                                <CommandPalette.ListItem
                                    key={id}
                                    index={getItemIndex(frontFilteredItems, id)}
                                    {...rest}
                                />
                            ))}
                        </CommandPalette.List>
                    ))
                ) : (
                    <CommandPalette.FreeSearchAction/>
                )}
            </CommandPalette.Page>
        </CommandPalette>
    }


};

export default Cmdk;
